package com.gmadmin.mq.template;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.gmadmin.entity.MqEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 测试发送消息模板
 *
 * @author zhangliang
 * @version 1.0
 * @date 2022/7/28 11:48
 */
@Service
public class TestMessageTemplate {

    // 需要使用topic全称，所以进行topic名称的拼接，也可以自己设置  格式：namespace全称%topic名称
    @Value("${rocketmq.namespace}%${rocketmq.producer1.topic}")
    private String topic;

    @Value("${rocketmq.producer1.tag}")
    private String tag;

    private final CustomMessageTemplate template;

    public TestMessageTemplate(CustomMessageTemplate template) {
        this.template = template;
    }

    /**
     * 同步发送消息
     *
     * @param orderId id
     * @param body    消息体
     */

    public void syncSendTest(@NotNull String orderId, String body) {
        MqEntity mqEntity = new MqEntity();
        mqEntity.setKey("id:" + orderId);
        mqEntity.setSource("测试同步消息发送");
        mqEntity.setMessage(body);

        mqEntity.setId(NanoIdUtils.randomNanoId());
        mqEntity.setUsername("测试同步发送");
        mqEntity.setTradeTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        template.syncSend(topic, tag, mqEntity);
    }

    public void sendMessageForTransaction(@NotNull String orderId, String body) {
        MqEntity mqEntity = new MqEntity();
        mqEntity.setKey("id:" + orderId);
        mqEntity.setSource("测试事务消息发送");
        mqEntity.setMessage(body);

        mqEntity.setId(NanoIdUtils.randomNanoId());
        mqEntity.setUsername("测试事务用户");
        mqEntity.setTradeTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));


        template.sendMessageForTransaction(topic, tag, mqEntity, "key-" + orderId);

    }
}
